package com.mdd.front.service.address.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.address.UserAddress;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.address.UserAddressMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.utils.TimeUtil;
import com.mdd.front.service.address.IUserAddressService;
import com.mdd.front.validate.address.UserAddressPageParam;
import com.mdd.front.validate.address.UserAddressParam;
import com.mdd.front.vo.address.UserAddressDetailVo;
import com.mdd.front.vo.address.UserAddressListVo;
import com.mdd.front.service.region.IDevRegionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 用户地址实现类
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {

    @Resource
    UserAddressMapper userAddressMapper;
    @Resource
    UserMapper userMapper;

    @Resource
    private IDevRegionService regionService;

    /**
     * 用户地址列表
     *
     * @param params 搜索参数
     * @return PageResult<UserAddressListVo>
     */
    @Override
    public PageResult<UserAddressListVo> list(UserAddressPageParam params) {
        Integer page = params.getPageNo();
        Integer limit = params.getPageSize();
        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAddress::getUserId, params.getUserId());
        queryWrapper.eq(UserAddress::getIsDelete, GlobalConstant.NOT_DELETE);
        queryWrapper.orderByDesc(UserAddress::getIsDefault);
        queryWrapper.orderByDesc(UserAddress::getCreateTime);
        IPage<UserAddress> iPage = userAddressMapper.selectPage(new Page<>(page, limit), queryWrapper);
        List<UserAddressListVo> list = new LinkedList<>();
        Map<Long, String> regionMap = regionService.getRegionMap();
        for (UserAddress item : iPage.getRecords()) {
            UserAddressListVo vo = new UserAddressListVo();
            BeanUtils.copyProperties(item, vo);
            vo.setProvince(regionMap.get(vo.getProvinceId()));
            vo.setCity(regionMap.get(vo.getCityId()));
            vo.setDistrict(regionMap.get(vo.getDistrictId()));
            vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 用户地址详情
     *
     * @param id 主键参数
     * @return UserAddress
     */
    @Override
    public UserAddressDetailVo detail(Long id) {
        UserAddress model = userAddressMapper.selectOne(
                new QueryWrapper<UserAddress>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        UserAddressDetailVo vo = new UserAddressDetailVo();
        Map<Long, String> regionMap = regionService.getRegionMap();
        BeanUtils.copyProperties(model, vo);
        vo.setProvince(regionMap.get(model.getProvinceId()));
        vo.setCity(regionMap.get(model.getCityId()));
        vo.setDistrict(regionMap.get(model.getDistrictId()));
        return vo;
    }

    /**
     * 用户地址新增
     *
     * @param userAddressParam 参数
     */
    @Override
    public void add(UserAddressParam userAddressParam) {
        if (userAddressParam.getIsDefault() == 1) {
            LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserAddress::getUserId, userAddressParam.getUserId());
            lambdaQueryWrapper.eq(UserAddress::getIsDefault, 1);
            lambdaQueryWrapper.last("limit 1");
            UserAddress address = super.getOne(lambdaQueryWrapper);
            if (address != null) {
                address.setIsDefault(0);
                super.updateById(address);
            }
        }
        UserAddress model = new UserAddress();
        model.setUserId(userAddressParam.getUserId());
        model.setContact(userAddressParam.getContact());
        model.setMobile(userAddressParam.getMobile());
        model.setProvinceId(userAddressParam.getProvinceId());
        model.setCityId(userAddressParam.getCityId());
        model.setDistrictId(userAddressParam.getDistrictId());
        model.setAddress(userAddressParam.getAddress());
        model.setLongitude(userAddressParam.getLongitude());
        model.setLatitude(userAddressParam.getLatitude());
        model.setIsDefault(userAddressParam.getIsDefault());
        model.setCreateTime(TimeUtil.timestamp());
        model.setUpdateTime(TimeUtil.timestamp());
        userAddressMapper.insert(model);
        User user = userMapper.selectById(userAddressParam.getUserId());
        user.setNickname(userAddressParam.getContact());
        user.setUsername(userAddressParam.getContact());
        user.setMobile(userAddressParam.getMobile());
        userMapper.updateById(user);
    }

    /**
     * 用户地址编辑
     *
     * @param userAddressParam 参数
     */
    @Override
    public void edit(UserAddressParam userAddressParam) {
        UserAddress model = userAddressMapper.selectOne(
                new QueryWrapper<UserAddress>()
                        .eq("id", userAddressParam.getId())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        if (userAddressParam.getIsDefault() == 1) {
            LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserAddress::getUserId, userAddressParam.getUserId());
            lambdaQueryWrapper.eq(UserAddress::getIsDefault, 1);
            lambdaQueryWrapper.last("limit 1");
            UserAddress address = super.getOne(lambdaQueryWrapper);
            if (address != null) {
                address.setIsDefault(0);
                super.updateById(address);
            }
        }

        model.setId(userAddressParam.getId());
        model.setUserId(userAddressParam.getUserId());
        model.setContact(userAddressParam.getContact());
        model.setMobile(userAddressParam.getMobile());
        model.setProvinceId(userAddressParam.getProvinceId());
        model.setCityId(userAddressParam.getCityId());
        model.setDistrictId(userAddressParam.getDistrictId());
        model.setAddress(userAddressParam.getAddress());
        model.setLongitude(userAddressParam.getLongitude());
        model.setLatitude(userAddressParam.getLatitude());
        model.setIsDefault(userAddressParam.getIsDefault());
        model.setUpdateTime(TimeUtil.timestamp());
        userAddressMapper.updateById(model);
    }

    /**
     * 用户地址删除
     *
     * @param id 主键ID
     */
    @Override
    public void del(Long id) {
        UserAddress model = userAddressMapper.selectOne(
                new QueryWrapper<UserAddress>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setDeleteTime(TimeUtil.timestamp());
        model.setIsDelete(GlobalConstant.DELETE);
        userAddressMapper.updateById(model);
    }

    @Override
    public UserAddressDetailVo getDefaultAddress(Long userId) {
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getUserId, userId);
        lambdaQueryWrapper.eq(UserAddress::getIsDelete, GlobalConstant.NOT_DELETE);
        lambdaQueryWrapper.orderByDesc(UserAddress::getIsDefault);
        lambdaQueryWrapper.last("limit 1");
        UserAddress one = super.getOne(lambdaQueryWrapper);
        if (null == one) {
            return null;
        }
        Map<Long, String> regionMap = regionService.getRegionMap();
        UserAddressDetailVo addressDetailVo = new UserAddressDetailVo();
        BeanUtils.copyProperties(one, addressDetailVo);
        addressDetailVo.setProvince(regionMap.get(one.getProvinceId()));
        addressDetailVo.setCity(regionMap.get(one.getCityId()));
        addressDetailVo.setDistrict(regionMap.get(one.getDistrictId()));
        return addressDetailVo;
    }

}
